package com.focusai.efairy.ui.base;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.focusai.efairy.R;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.network.exception.ServerException;
import com.focusai.efairy.ui.activity.global.ReloginDialogActivity;
import com.focusai.efairy.ui.widget.WaitingDialog;
import com.focusai.efairy.utils.Constants;
import com.focusai.efairy.utils.ErrorCodeUtils;
import com.focusai.efairy.utils.log.Log;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * BaseFragmentActivity
 */
public abstract class BaseFragmentActivity extends AppCompatActivity {
    public static final int MENU_GROUP_ID = 100;
    public static final int MENU_ITEM_SAVE = MENU_GROUP_ID + 1;
    public static final int MENU_ITEM_ADD = MENU_GROUP_ID + 2;
    public static final int MENU_ITEM_EDIT = MENU_GROUP_ID + 3;
    public static final int MENU_ITEM_FILTER = MENU_GROUP_ID + 4;
    public static final int MENU_ITEM_SETTING = MENU_GROUP_ID + 5;
    public static final int MENU_ITEM_LIST = MENU_GROUP_ID + 6;
    public static final int MENU_ITEM_ADD_GROUP = MENU_GROUP_ID + 7;
    public static final int MENU_ITEM_PRINT = MENU_GROUP_ID + 8;
    public static final int MENU_ITEM_SCANMODE = MENU_GROUP_ID + 9;
    public static final int MENU_ITEM_REFRESH = MENU_GROUP_ID + 10;
    private static final String TAG = "YS.BaseFragmentActivity";
    private Toolbar toolbar;
    // --------------------------------------------------------------------
    // ------------------------- Common message code ----------------------

    // --------------------------------------------------------------------

    protected Context mContext;

    private Toast mToast;

    private PermissionListener permissionListener = null;

    /**
     * 界面更新相关操作消息处理handler
     */
    private Handler mUiHandler;

    /**
     * 耗时操作需在此handler处理
     */
    private Handler mProcHandler;

    /**
     * 子线程
     */
    private HandlerThread mProcThread;

    private WaitingDialog waitingDialog;//一个界面一个弹框
    private TextView txtCenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        super.setContentView(R.layout.activity_base_layout);
        toolbar = findView(R.id.common_toolbar);

        if (!hasActionBar())// 没有ActionBar/Toolbar的时候
        {
            if (getSupportActionBar() != null)
                getSupportActionBar().hide();
            toolbar.setVisibility(View.GONE);
            findViewById(R.id.line_view).setVisibility(View.GONE);
        } else {// 有ActionBar/Toolbar的时候，将ToolBar关联到ActionBar上去//后面操作的时候最好用getToolBar方法而不是getActionBar//虽然可能没什么大问题
            setSupportActionBar(toolbar);
        }

        if (getSupportActionBar() != null) {
            // 设置图标
            getSupportActionBar().setIcon(R.drawable.selector_actionbar_back_btn);
            // 设置Logo
            // getSupportActionBar().setLogo(R.drawable.ic_launcher);

            // 显示左上角"返回"图标
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeAsUpIndicator(R.drawable.selector_actionbar_back_btn);

            // 显示标题
            // getSupportActionBar().setDisplayShowTitleEnabled(false);
            // R.id.home区域可点击

            // 显示返回+title
            getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP);
        }

        txtCenter = findView(R.id.txt_center);

        if (useHandleThread()) {
            mProcThread = new HandlerThread(this.getClass().getName());
            // mProcThread.setPriority(Thread.MIN_PRIORITY); //设置线程优先级
            mProcThread.start();

            mUiHandler = new Handler(this.getMainLooper(), new Handler.Callback() {

                @Override
                public boolean handleMessage(Message msg) {
                    return uiHandlerCallback(msg);
                }
            });

            mProcHandler = new Handler(mProcThread.getLooper(), new Handler.Callback() {

                @Override
                public boolean handleMessage(Message msg) {
                    return procHandlerCallback(msg);
                }
            });
        }

        initTitte();
    }    // &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ActionBar Handler &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


    protected boolean useHandleThread() {
        return false;
    }

    @Override
    public void setContentView(int layoutResID) {
        LayoutInflater inflater = LayoutInflater.from(this);
        FrameLayout parentView = ((FrameLayout) findViewById(R.id.base_root_content));
        inflater.inflate(layoutResID, parentView);

        onSupportContentChangedExt();
    }

    public void onSupportContentChangedExt() {

    }

    public TextView getCenterTextView() {
        txtCenter.setVisibility(View.VISIBLE);
        return txtCenter;
    }


    public void initTitte() {

    }

    public void setCenterTitleName(int resId) {
        txtCenter.setVisibility(View.VISIBLE);
        txtCenter.setText(resId);
    }

    public void setCenterTitleName(String text) {
        txtCenter.setVisibility(View.VISIBLE);
        txtCenter.setText(text);
    }

    public Toolbar getToolbar() {
        return toolbar;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                // 默认对Home区域做"返回"处理.
                onActionBarBackClick();
                break;
            }
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 需要在ui线程执行
     *
     * @return
     */
    protected WaitingDialog getSingleDialog() {
        if (waitingDialog == null) {
            waitingDialog = new WaitingDialog(BaseFragmentActivity.this);
        }
        return this.waitingDialog;
    }

    protected void showSingleDialog(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(BaseFragmentActivity.this);
                }
                waitingDialog.setMessage(msg);
                waitingDialog.show();
            }
        });
    }

    /**
     * 一个不能被取消的Dialog
     *
     * @param msg 显示的信息
     */
    public void showNotCancelableDialog(String msg) {
        Dialog dialog = getSingleDialog();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        showSingleDialog(msg);
    }

    public void closeSingleDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (waitingDialog != null && (waitingDialog.isShowing())) {
                    waitingDialog.cancel();
                }
            }
        });

    }

    /**
     * 设置标题
     *
     * @param resId
     */
    public void setActionBarTitle(int resId) {
        if (getSupportActionBar() != null)
            getSupportActionBar().setTitle(resId);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setActionBarTitle(CharSequence title) {
        if (getSupportActionBar() != null)
            getSupportActionBar().setTitle(title);
    }

    /**
     * 设置Home图标
     *
     * @param resId
     */
    public void setActionBarIcon(int resId) {
        if (getSupportActionBar() != null)
            getSupportActionBar().setIcon(resId);
    }

    /**
     * 设置Home图标
     *
     * @param icon
     */
    public void setActionBarIcon(Drawable icon) {
        if (getSupportActionBar() != null)
            getSupportActionBar().setIcon(icon);
    }

    /**
     * 设置显示方式
     *
     * @param options
     * @param mask
     */
    public void setActionBarDisplayOptions(int options, int mask) {
        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayOptions(options, mask);
    }

    /**
     * ActionBar的返回操作, 依赖于是否已经重写onActionBarHomeClick().
     * onActionBarHomeClick()返回true, 则表示已经消费引事件, 反之, 则由父类统一处理.
     */
    protected void onActionBarBackClick() {
        if (!onActionBarHomeClick()) {
            finish();
        }
    }

    /**
     * 点击Home
     */
    protected boolean onActionBarHomeClick() {
        return false;
    }

    /**
     * 是否需要显示ActionBar, hide()后会延时一会再完全消失.
     *
     * @return
     */
    protected boolean hasActionBar() {
        return true;
    }

    // &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ActionBar Handler &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

    @Override
    protected void onResume() {
        super.onResume();
    }

    protected void onResume(boolean umeng) {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    protected void onPause(boolean umeng) {
        super.onPause();
    }


    @Override
    protected void onDestroy() {

        if (mProcThread != null) {
            mProcThread.quit();
            mProcThread = null;
        }
        if (mProcHandler != null) {
            mProcHandler.removeCallbacksAndMessages(null);//移除消息队列中所有消息和所有的Runnable
        }
        if (mUiHandler != null) {
            mUiHandler.removeCallbacksAndMessages(null);//移除消息队列中所有消息和所有的Runnable
        }
        Log.D(TAG, "onDestroy");
        super.onDestroy();
    }

    /**
     * 是否为根入口
     *
     * @return
     */
    protected boolean isRootActivity() {
        return false;
    }

    public Context getContext() {
        return mContext;
    }

    protected Handler getUiHandler() {
        return mUiHandler;
    }

    public Handler getProcHandler() {
        return mProcHandler;
    }

    private Handler.Callback mUiHandlerCallback = new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            return uiHandlerCallback(msg);
        }
    };

    private Handler.Callback mProcHandlerCallback = new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            return procHandlerCallback(msg);
        }
    };


    /**
     * UI更新请求消息处理函数
     * <p/>
     * 子类可重载此函数，已处理自己的私有消息
     *
     * @param msg
     * @return
     */
    protected boolean uiHandlerCallback(Message msg) {
        return false;
    }

    /**
     * 与界面无关的操作消息处理函数
     * <p/>
     * 子类可重载此函数，已处理自己的私有消息
     *
     * @param msg
     * @return
     */
    protected boolean procHandlerCallback(Message msg) {
        return false;
    }

    /**
     * Init view.
     */
    protected void initView() {

    }

    /**
     * Set default value to target view, or other object.
     */
    protected void setDefaultValues() {

    }

    /**
     * Bind events to target view.
     */
    protected void bindEvents() {

    }

    protected void loadData() {

    }

    public void showToast(String info) {
        if (mToast == null) {
            mToast = Toast.makeText(this, info, Toast.LENGTH_SHORT);

            DisplayMetrics dm = new DisplayMetrics();
            this.getWindowManager().getDefaultDisplay().getMetrics(dm);

            mToast.setGravity(Gravity.TOP, 0, dm.heightPixels / 5);
        } else {
            mToast.setText(info);
        }

        mToast.show();
    }

    public void showToast(int resId) {
        if (mToast == null) {
            mToast = Toast.makeText(this, resId, Toast.LENGTH_SHORT);

            DisplayMetrics dm = new DisplayMetrics();
            this.getWindowManager().getDefaultDisplay().getMetrics(dm);

            mToast.setGravity(Gravity.TOP, 0, dm.heightPixels / 5);
        } else {
            mToast.setText(resId);
        }

        mToast.show();
    }

    public void showToastOnUiThread(final int resId) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                showToast(resId);
            }
        });
    }

    public void showToastOnUiThread(final String info) {
        if (info == null)
            return;
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                showToast(info);
            }
        });
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftInput() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // --------------- Normal Functions End ---------------------------------


    public <T extends View> T findView(int id) {
        return (T) this.findViewById(id);
    }

    public void doException(Exception exception) {
        doException(exception, true);
    }

    public void doException(Exception exception, boolean show) {
        if (exception != null) {
            if (exception instanceof ServerException) {
                String errorMessage = ((ServerException) exception).getErrorMessage();
                if (ErrorCodeUtils.needReLogin(((ServerException) exception).getErrorCode())){ //是否需要重新登录
                    doLoginOnOther(errorMessage);
                }else {
                    showToastOnUiThread(errorMessage);
                }
            } else if (exception instanceof NetworkException) {
                showToastOnUiThread(((NetworkException) exception).getErrorMessage());
            }
        } else if (show) {
            showToastOnUiThread(R.string.error_network);
        }
    }
    /**
     * 在需要检测权限处调用该方法，同时实现回调接口即可
     *
     * @param requestCode
     * @param permissionListener
     * @param permissions
     */
    public void checkPermission(int requestCode, @NonNull PermissionListener permissionListener, @NonNull String... permissions) {
        this.permissionListener = permissionListener;
        if (PermissionUtil.hasPermission(this, permissions)) {
            List<String> grantedList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                grantedList.add(permissions[i]);
            }
            permissionListener.onSucceed(requestCode, grantedList);
        } else {
            PermissionUtil.requestPermissions(this, requestCode, permissions);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionListener != null) {
            PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, permissionListener);
        }
    }

    protected void doLoginOnOther(String msg){
        Intent intent = new Intent(mContext, ReloginDialogActivity.class);
        intent.putExtra(Constants.RE_LOGIN_TIME, 0);
        intent.putExtra(Constants.RE_LOGIN_MSG, msg);
        mContext.startActivity(intent);
    }
}
